import grace from "../../utils/grace.js"
grace.page({
  data: {
    imgUrls: [
      {
        link: '/pages/index/index',
        cover_img: '../../image/banner.png'
      }
    ],
    searchParam: {
      pageSize: 10,
      pageCurrent: 1
    },
    recomment:[],
    hasMore:false
  },
  onLoad: function (options) {
    this.loadData();
  },
  onShow:function(){
    //避免页面停留时间太急，数据没有更新
    let that = this;
    wx.getStorage({
      key: 'goods_expire_date',
      success: function (res) {
        let expire_date = res.data;
        let today = new Date().getTime();
        if (expire_date != undefined && parseInt(expire_date) < today) {
          that.loadData();
        }
      }
    });
  },
  loadData:function(){
    this.$http.get("api/goods/list", this.data.searchParam).then((res) => {
      wx.stopPullDownRefresh();
      var isHasMore = res.list.length >= this.$data.searchParam.pageSize;
      const data = this.$data.searchParam.pageCurrent == 1 ? res.list : this.$data.recomment.concat(res.list);
      this.$data = {
        recomment: data,
        hasMore: isHasMore
      };

      // 
      let myDate = new Date();
      let expire_date = myDate.getTime() + 1000 * 60 * 1;
      wx.setStorage({
        key: 'goods_expire_date',
        data: expire_date,
      });
    });
  },
  addToCart:function(e){
    let goods_id = e.currentTarget.dataset.goods;
    this.$http.post('api/cart/add_goods', { goods_vals: goods_id}).then((res)=>{
      this.toast(res.message);
      // setTimeout(function () {
      //   grace.bus.$emit("update_cart_event");
      // }, 500);
    });
  },
  openDetail: function (e) {
    let goods_id = e.currentTarget.dataset.goods;
    wx.navigateTo({
      url: '../product_details/product_details?goods_id=' + goods_id,
    })
  },
  openMenuDetail: function (e) {
    var menu = e.currentTarget.dataset.menu;
    wx.navigateTo({
      url: '../menu_recommend/menu_recommend?menu_id=' + menu,
    })
  },
  onReachBottom: function () {
    if (this.$data.hasMore) {
      ++this.$data.searchParam.pageCurrent;
      this.loadData();
    }
  },
  onPullDownRefresh: function () {
    this.$data.searchParam.pageCurrent = 1;
    this.loadData();
  },
  onShareAppMessage: function () {
    let user_id = wx.getStorageSync('user_id');
    let from_store = wx.getStorageSync('current_store');
    return {
      title: '商品列表',
      path: '/pages/goods/goods?from_user=' + user_id + '&from_store=' + from_store,
      success: function (res) {

      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})